package com.lxq.web.servlet.mng;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.lxq.common.DaoFactory;
import com.lxq.dao.UserDao;
import com.lxq.entity.User;
import com.lxq.web.servlet.common.BaseServlet;

@WebServlet("/app/mng/user")
public class UserServlet extends BaseServlet {

	private static final long serialVersionUID = -120594264735680174L;
	private UserDao userDao = DaoFactory.getInstance("userDao", UserDao.class);

	@Override
	public void doEdit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String newphone = request.getParameter("newphone");
		String phone = request.getParameter("phone");

		User user = userDao.findByPhone(phone);
		JSONObject json = new JSONObject();
		Object[] paramValues = null;
		boolean flag = true;

		String sql = "update user set userName=?, password=?, phoneNumber=? where phoneNumber=?";

		try {
			if (user != null) {
				if (!username.equalsIgnoreCase("")) {

					user.setUserName(username);
					json.put("reason", "编辑用户名");

				}
				if (!password.equalsIgnoreCase("")) {

					Pattern p = Pattern.compile("\\d{4,}");
					Matcher m = p.matcher(password);
					if (!m.matches()) {
						flag = false;
						json.put("reason", "密码至少4位以上！");
					} else {
						user.setPassword(password);
						json.put("reason", "更新密码");
					}
				}
				if (!newphone.equalsIgnoreCase("")) {

					Pattern p = Pattern.compile("[1][3458]\\d{9}");
					Matcher m = p.matcher(newphone);
					if (!m.matches()) {
						flag = false;
						json.put("reason", "手机号码不合法！");
					} else {
						user.setPhoneNumber(newphone);
						json.put("reason", "重新绑定手机");
					}

				}

				paramValues = new Object[] { user.getUserName(), user.getPassword(), user.getPhoneNumber(), phone };

				if(flag == true){
					userDao.update(sql, paramValues);
					json.put("success", true);
				}else{
					json.put("success", false);
				}
			} else {
				json.put("success", false);
				json.put("reason", "未注册的用户！");
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().print(json.toString());
		response.getWriter().flush();
	}

}
